// pages/forgetPassword/index.js
var app = getApp()
import _config from '../../utils/config';
import _fetch from '../../utils/httpService';
import util from '../../utils/util';
import {
  hexMD5
} from '../../utils/md5';
let timer = null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    focusPhoneNumber: false,
    valuePhoneNumber: '',
    valuePhoneNumberTemp: '',
    isPhoneNumberClearShow: false,
    focusVerify: false,
    valueVerify: '',
    verifyText: '获取验证码',
    isVerifyEnable: false,
    focusPassword: false,
    valuePassword: '',
    isPasswordShow: false,
    focusPassword2: false,
    valuePassword2: '',
    isPasswordShow2: false,
    isLoginEnabled: false,
    showModalPhoneNumberInput: false,
    showModalPasswordInput: false,
    showModalPasswordDifferent: false,
    showModalVerifyInput: false,
    showModalUnRegedit: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.login({
      success: res => {
        getApp().globalData.ownCode = res.code
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    // if (timer) {
    //   this.setData({
    //     verifyText: '获取验证码',
    //     isVerifyEnable: true,
    //   });
    //   clearInterval(timer);
    // }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if (timer) {
      this.setData({
        verifyText: '获取验证码',
        isVerifyEnable: true,
      });
      clearInterval(timer);
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '助力企业工单管理智能升级', // 分享标题
      desc: '', // 分享描述
      path: '/pages/login/index', // 分享路径
      imageUrl: '../../img/Mask.png' // 分享图片
    }
  },
  changeEnterprise(id) {
    // 选择企业
    getApp().globalData.enterpriseId = id
    let url = _config.url.choose_enterprise.replace('{id}', id);
    _fetch.get(url)
      .then(function (res) {
        getApp().globalData.userData = res;
        if (app.globalData.isService) {
          wx.redirectTo({
            url: '../catchOrder/index'
          })
        } else {
          wx.redirectTo({
            url: '../order/index'
          })
        }
      }).catch(function (error) {
        wx.showToast({
          title: error.msg,
          icon: 'none',
        });
      });
  },
  // 登录成功处理
  loginComplete: function (data) {
    console.log(data)
    let vm = this
    wx.setStorageSync('infoPhoneNumber', this.data.valuePhoneNumber);
    wx.setStorageSync('infoPassword', this.data.valuePassword);
    wx.setStorageSync('sessionId', data.sessionId);
    _fetch.setHeader('session_id', data.sessionId);
    if (data.enterprises && data.enterprises.length > 0) {
      vm.changeEnterprise(data.enterprises[0].id)
    }
    _fetch.get(_config.url.get_perms)
      .then(function (res) {
        getApp().globalData.perms = res;
      }).catch(function (error) {
        wx.showToast({
          title: error.msg,
          icon: 'none',
        });
      });
  },
  // 登录
  fetchLogin: function () {
    let vm = this
    _fetch.setHeader('T-App-Type', 'IFORM_MINIPROGRAM');
    let requestData = {
      type: 0,
      username: vm.data.valuePhoneNumber,
      password: hexMD5(vm.data.valuePassword),
      code: null,
      wxCode: app.globalData.ownCode
    };
    _fetch.post(_config.url.bind, requestData)
      .then(function (data) {
        vm.loginComplete(data);
      }).catch(function (error) {
        vm.loginError(error);
      });
  },

  // 修改密码成功处理
  submitComplete: function () {
    this.fetchLogin();
  },
  // 修改密码
  fetchSubmit: function () {
    let _this = this;
    let requestData = {
      password: hexMD5(this.data.valuePassword),
      mobile: this.data.valuePhoneNumber,
      code: this.data.valueVerify,
    };
    _fetch.put(_config.url.reset_psd, requestData)
      .then(function (data) {
        _this.submitComplete();
      }).catch(function (error) {
        wx.showToast({
          title: error.msg,
          icon: 'none',
        });
      });
  },
  // 启动定时器
  startTimer: function () {
    let _this = this;
    let second = 60;
    _this.setData({
      verifyText: --second + 's',
      isVerifyEnable: false,
    });
    timer = setInterval(
      function () {
        if (second < 1) {
          _this.setData({
            verifyText: '获取验证码',
            isVerifyEnable: true,
          });
          clearInterval(timer);
        } else {
          _this.setData({
            verifyText: --second + 's',
          });
        }
      },
      1000
    );
  },
  // 获取登录验证码
  fetchVerifyCode: function () {
    let vm = this;
    let sign = String(this.data.valuePhoneNumber) + String(Date.now()) + '2go8gnciqusrpzthmjqr2jvwykp6qxhh'
    let requestData = {
      mobile: this.data.valuePhoneNumber,
      timestamp: Date.now(),
      sign: hexMD5(sign)
    }
    vm.startTimer();
    _fetch.post(_config.url.get_valid_code, requestData)
      .then(function (data) {

      }).catch(function (error) {
        wx.showToast({
          title: '获取验证码失败',
          icon: 'none',
        });
      });
  },

  // 点击手机号输入框事件
  tapPhoneNumberBox: function (event) {
    this.setData({
      focusPhoneNumber: true,
      focusVerify: false,
      focusPassword: false,
      focusPassword2: false,
    });
  },
  // 点击验证码输入框事件
  tapVerifyBox: function (event) {
    this.setData({
      focusPhoneNumber: false,
      focusVerify: true,
      focusPassword: false,
      focusPassword2: false,
    });
  },
  // 点击密码输入框事件
  tapPasswordBox: function (event) {
    this.setData({
      focusPhoneNumber: false,
      focusVerify: false,
      focusPassword: true,
      focusPassword2: false,
    });
  },
  // 点击密码2输入框事件
  tapPasswordBox2: function (event) {
    this.setData({
      focusPhoneNumber: false,
      focusVerify: false,
      focusPassword: false,
      focusPassword2: true,
    });
  },
  // 输入手机号事件
  inputPhoneNumber: function (event) {
    if (event.detail.value) {
      let isLoginEnabled = false;
      if (this.data.valueVerify && this.data.valuePassword && this.data.valuePassword2) {
        isLoginEnabled = true;
      }
      this.setData({
        valuePhoneNumber: event.detail.value,
        isPhoneNumberClearShow: true,
        isVerifyEnable: true,
        isLoginEnabled: isLoginEnabled,
      });
    } else {
      this.setData({
        valuePhoneNumber: event.detail.value,
        isPhoneNumberClearShow: false,
        isVerifyEnable: false,
        isLoginEnabled: false,
      });
    }
  },
  // 输入验证码事件
  inputVerify: function (event) {
    if (event.detail.value) {
      let isLoginEnabled = false;
      if (this.data.valuePhoneNumber && this.data.valuePassword && this.data.valuePassword2) {
        isLoginEnabled = true;
      }
      this.setData({
        valueVerify: event.detail.value,
        isLoginEnabled: isLoginEnabled,
      });
    } else {
      this.setData({
        valueVerify: event.detail.value,
        isLoginEnabled: false,
      });
    }
  },
  // 输入密码事件
  inputPassword: function (event) {
    if (event.detail.value) {
      let isLoginEnabled = false;
      if (this.data.valuePhoneNumber && this.data.valueVerify && this.data.valuePassword2) {
        isLoginEnabled = true;
      }
      this.setData({
        valuePassword: event.detail.value,
        isLoginEnabled: isLoginEnabled,
      });
    } else {
      this.setData({
        valuePassword: event.detail.value,
        isLoginEnabled: false,
      });
    }
  },
  // 输入密码2事件
  inputPassword2: function (event) {
    if (event.detail.value) {
      let isLoginEnabled = false;
      if (this.data.valuePhoneNumber && this.data.valueVerify && this.data.valuePassword) {
        isLoginEnabled = true;
      }
      this.setData({
        valuePassword2: event.detail.value,
        isLoginEnabled: isLoginEnabled,
      });
    } else {
      this.setData({
        valuePassword2: event.detail.value,
        isLoginEnabled: false,
      });
    }
  },
  // 点击手机号清空事件
  tapPhoneNumberClear: function (event) {
    this.setData({
      valuePhoneNumber: '',
      valuePhoneNumberTemp: '',
      isPhoneNumberClearShow: false,
      isVerifyEnable: false,
      isLoginEnabled: false,
    });
  },
  // 点击密码显示隐藏事件
  tapPasswordShowHide: function (event) {
    this.setData({
      isPasswordShow: !this.data.isPasswordShow,
    });
  },
  // 点击密码2显示隐藏事件
  tapPasswordShowHide2: function (event) {
    this.setData({
      isPasswordShow2: !this.data.isPasswordShow2,
    });
  },
  // 点击获取验证码事件
  tapVerify: function (event) {
    if (this.data.verifyText != '获取验证码') {
      return;
    }
    let isPhoneNumberOk = util.checkMobilePhoneNumber(this.data.valuePhoneNumber);
    if (!isPhoneNumberOk) {
      wx.showToast({
        title: '请输入正确手机号',
        icon: 'none'
      })
      return;
    }
    this.fetchVerifyCode();
  },
  // 点击修改密码并登录事件
  tapLogin: function () {
    let isPhoneNumberOk = util.checkMobilePhoneNumber(this.data.valuePhoneNumber);
    if (!isPhoneNumberOk) {
      wx.showToast({
        title: '请输入正确手机号',
        icon: 'none'
      })
      return;
    }
    let isPasswordOk = util.checkPassword(this.data.valuePassword);
    if (!isPasswordOk) {
      wx.showToast({
        title: '密码6~16位数字或字母，区分大小写',
        icon: 'none'
      })
      return;
    }
    if (this.data.valuePassword != this.data.valuePassword2) {
      wx.showToast({
        title: '两次密码不一致',
        icon: 'none'
      })
      return;
    }
    this.fetchSubmit();
  },

  // 点击输入手机号确定事件
  phoneNumberInputConfirm: function (event) {
    this.setData({
      focusPhoneNumber: true,
      showModalPhoneNumberInput: false,
    });
  },
  // 点击输入密码确定事件
  passwordInputConfirm: function (event) {
    this.setData({
      focusPassword: true,
      showModalPasswordInput: false,
    });
  },

  // 点击密码不一致确定事件
  passwordDifferentConfirm: function (event) {
    this.setData({
      focusPassword2: true,
      showModalPasswordDifferent: false,
    });
  },

  // 点击输入验证码确定事件
  verifyInputConfirm: function (event) {
    this.setData({
      focusVerify: true,
      showModalVerifyInput: false,
    });
  }
})